package com.lyzbbb.demo.miniapp.controller;

import com.lyzbbb.demo.miniapp.entity.Student;
import com.lyzbbb.demo.miniapp.service.StudentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.text.SimpleDateFormat;
import java.util.HashMap;
import java.util.Map;
import java.util.Optional;
import java.util.logging.Logger;

/**
 * 学生API接口控制器
 */
@RestController
@RequestMapping("/api/student")
@CrossOrigin(origins = "*") // 允许跨域请求，以便小程序调用
public class StudentController {

    private static final Logger logger = Logger.getLogger(StudentController.class.getName());
    private final StudentService studentService;
    private final SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");

    @Autowired
    public StudentController(StudentService studentService) {
        this.studentService = studentService;
    }

    /**
     * 根据学号查询学生
     * @param id 学号
     * @return 学生信息
     */
    @GetMapping("/{id}")
    public ResponseEntity<?> getStudentById(@PathVariable String id) {
        logger.info("接收到查询请求，学号: " + id);
        Optional<Student> student = studentService.findById(id);
        
        if (student.isPresent()) {
            Map<String, String> response = new HashMap<>();
            response.put("id", student.get().getId());
            response.put("name", student.get().getName());
            
            // 添加出生日期信息
            if (student.get().getBirthDate() != null) {
                String formattedDate = dateFormat.format(student.get().getBirthDate());
                logger.info("学生出生日期: " + formattedDate);
                response.put("birthDate", formattedDate);
            } else {
                logger.warning("学生出生日期为null");
                response.put("birthDate", "");
            }
            
            logger.info("返回数据: " + response);
            return ResponseEntity.ok(response);
        } else {
            logger.warning("未找到学生, id: " + id);
            Map<String, String> error = new HashMap<>();
            error.put("message", "未找到学号为 " + id + " 的学生");
            error.put("suggestion", "可用学号范围: 202001001-202001005");
            return ResponseEntity.status(HttpStatus.NOT_FOUND).body(error);
        }
    }

    /**
     * 保存学生信息（仅用于测试）
     * @param student 学生对象
     * @return 保存结果
     */
    @PostMapping("/")
    public ResponseEntity<?> saveStudent(@RequestBody Student student) {
        Student savedStudent = studentService.save(student);
        return ResponseEntity.ok(savedStudent);
    }
} 